package cn.elegent.tx.core.manager.task.strategys.timer;

import cn.elegent.ac.ElegentAC;
import cn.elegent.tx.config.RollBackConfig;
import cn.elegent.tx.core.entity.TransactionEntity;
import cn.elegent.tx.core.entity.state.TransactionState;
import cn.elegent.tx.core.manager.TransactionManagerImpl;
import cn.elegent.tx.core.manager.task.LoopJob;
import cn.elegent.tx.core.rollback.RollBackDTO;
import cn.elegent.tx.core.storage.TransactionStorage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


/**
 * JDKTimerImpl
 * @description JDK自带的定时任务实现循环发送回滚消息的任务
 * @author WGL
 * @date 2022/11/7 18:25
*/
@ConditionalOnProperty(prefix="cn.elegent.actx",value = "task",havingValue = "timer",matchIfMissing = true)
@Component
@Slf4j
public class JDKTimerImpl implements LoopJob {

    @Autowired
    private RollBackConfig rollBackConfig;

    @Autowired(required = false)
    private ElegentAC elegentAC;
    
    @Autowired
    private TransactionStorage transactionStorage;
    
    @Override
    public void sendRollBackMsg(TransactionEntity transactionEntity, TransactionState success) {
        log.info("call JDKTimerImpl.sendRollBackMsg");
        //设置最大次数
        int maxTimes = rollBackConfig.getMaxCycles();
        // 1、创建 Timer 对象
        Timer timer = new Timer();
        // 2、创建 TimerTask 任务线程
        TimerTask timerTask = new TimerTask() {
            int times = 0;
            @Override
            public void run() {
                if(times<maxTimes) {
                    //3.1 查询所有需要发送的消息
                    List<RollBackDTO> allNeedRollBackInfo = transactionStorage.getAllNeedRollBackInfo(transactionEntity, success);
                    for (RollBackDTO dto : allNeedRollBackInfo) {
                        log.info("主题："+TransactionManagerImpl.ROLLBACK_TOPIC+dto.getServerName()+"发送回滚消息："+dto);
                        elegentAC.publish(TransactionManagerImpl.ROLLBACK_TOPIC+dto.getServerName(),dto);
                    }
                }else{
                    timer.cancel();
                }
                times++;
            }
        };
        // 4、启动定时任务，3秒之后执行一次定时任务
        timer.schedule(timerTask, rollBackConfig.getWaitTime());
    }
}
